# -*- coding: utf-8 -*- 
# @Time : 2021/7/11 17:19 
# @Author : Dong 
# @File : demo03_logger.py

import logging.config
from flask import Flask, jsonify
from flask_restful import Api, Resource, reqparse

logging.config.dictConfig(
    {
        "version": 1,
        "disable_existing_loggers": False,
        "formatters": {
            "simple": {"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"}
        },
        "handlers": {
            "console": {
                "class": "logging.StreamHandler",
                "level": "DEBUG",
                "formatter": "simple",
                "stream": "ext://sys.stdout",
            },
            "info_file_handler": {
                "class": "logging.handlers.RotatingFileHandler",
                "level": "INFO",
                "formatter": "simple",
                "filename": "info.log", # 文件地址
                "maxBytes": 10485760,  # 文件大小
                "backupCount": 50,  # 文件数量
                "encoding": "utf8",  # 文件的编辑格式
            },
            "error_file_handler": {
                "class": "logging.handlers.RotatingFileHandler",
                "level": "ERROR",
                "formatter": "simple",
                "filename": "errors.log",
                "maxBytes": 10485760,
                "backupCount": 20,
                "encoding": "utf8",
            },
            "debug_file_handler": {
                "class": "logging.handlers.RotatingFileHandler",
                "level": "DEBUG",
                "formatter": "simple",
                "filename": "debug.log",
                "maxBytes": 10485760,
                "backupCount": 50,
                "encoding": "utf8",
            },
        },
        "loggers": {
            "my_module": {"level": "ERROR", "handlers": ["console"], "propagate": "no"}
        },
        "root": {
            "level": "DEBUG",
            "handlers": ["error_file_handler", "debug_file_handler"],
        },
    }
)

app = Flask(__name__)
api = Api(app,default_mediatype='application/json')

user = [
    {'name':'djy'}
]

class User(Resource):
    def __init__(self, **kargs):
        self.logger = kargs.get('logger')

    def get(self):
        print(user)
        return user

    def post(self):
        args = reqparse.RequestParser().add_argument("name",type=str,location='json',required=True,help="name is not None").parse_args()
        print(args)

        self.logger.debug(args)

        if args.values() not in [i.values() for i in user]:
            user.append({"name":args["name"]})
        return jsonify(user)

    def delete(self):
        global user
        user = []
        return jsonify(user)

class User_name(Resource):
    def get(self,user_id):
        try:
            user_name = {'name':user[int(user_id)-1].get("name")}
            print(user_name)
        except Exception as e:
            return jsonify({'ERROR':"None"})
        return jsonify(user_name)

api.add_resource(User,"/users",resource_class_kwargs={"logger": logging.getLogger('/Users')})
api.add_resource(User_name,'/users/<user_id>',resource_class_kwargs={"logger": logging.getLogger('/Users')})

if __name__ == '__main__':
    app.run(debug=True)